﻿using System.Web;
using System.IO;

namespace HXDNB.Infrastructure.Helper
{
    public class Upload
    {
        public static string UpLoadImg(string fileName, string upPath = "~/Upload/")
        {
            try
            {
                //上传和返回(保存到数据库中)的路径
                if (HttpContext.Current.Request.Files.Count > 0)
                {
                    var imgFile = HttpContext.Current.Request.Files[fileName];
                    if (imgFile != null)
                    {                    
                        //获得上传图片的路径
                        string strPath = imgFile.FileName;
                        //获得上传图片的类型(后缀名)
                        string type = strPath.Substring(strPath.LastIndexOf(".", System.StringComparison.Ordinal) + 1).ToLower();
                        if (ValidateImg(type))
                        {
                            //拼写上传图片的路径
                            string uppath = HttpContext.Current.Server.MapPath(upPath);
                            if (!Directory.Exists(uppath))
                            {
                                Directory.CreateDirectory(uppath);
                            }
                            uppath += imgFile.FileName;
                            //上传图片
                            imgFile.SaveAs(uppath);
                            return imgFile.FileName;
                        }
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        private static bool ValidateImg(string imgName)
        {
            var imgType = new[] { "gif", "jpg", "png", "bmp" };
            int i = 0;
            bool blean = false;
            //判断是否为Image类型文件
            while (i < imgType.Length)
            {
                if (imgName.Equals(imgType[i]))
                {
                    blean = true;
                    break;
                }
                if (i == (imgType.Length - 1))
                    break;
                i++;
            }
            return blean;
        }
    }
}
